package com.example.gridviewtest;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.concurrent.Future;

public class FruitAdapter extends ArrayAdapter<Fruit> {

    private final ArrayList<Fruit> fruits;
    private final int resource;
    private final Context context;


    public FruitAdapter(Context context, int resource, ArrayList<Fruit> fruits) {
        super(context, resource, fruits);
        this.context = context;
        this.fruits = fruits;
        this.resource = resource;
    }


    class ViewHolder {

        ImageView ivFruit;
        TextView tvName;
    }


    @Override
    public int getCount() {
        return fruits.size();
    }

    @Override
    public Fruit getItem(int position) {
        return fruits.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Fruit fruit = getItem(position);
        View view;
        ViewHolder viewHolder;
        if (convertView == null) {
            view =  LayoutInflater.from(context).inflate(resource, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.ivFruit = view.findViewById(R.id.iv_fruit);
            viewHolder.tvName = view.findViewById(R.id.tv_name);
            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }

        viewHolder.ivFruit.setImageResource(fruit.getImageId());
        viewHolder.tvName.setText(fruit.getName());
        return view;
    }
}
